package org.basic.algorithm.simple.offer;

/**
 * 给定两个 01 字符串 a 和 b ，请计算它们的和，并以二进制字符串的形式输出。
 * <p>
 * 输入为 非空 字符串且只包含数字 1 和 0。
 * <p>
 * 示例 1:
 * 输入: a = "11", b = "10"
 * 输出: "101"
 * <p>
 * 示例 2:
 * 输入: a = "1010", b = "1011"
 * 输出: "10101"
 *
 * @author LiKun
 * @date 2021/10/28 10:59
 */
public class BinaryAddition {
    public static void main(String[] args) {
        System.out.println(addBinary("0", "0"));
    }

    public static String addBinary(String a, String b) {
        char[] charsA = a.toCharArray();
        char[] charsB = b.toCharArray();
        char[] result = new char[Math.max(charsA.length, charsB.length) + 1];
        BinaryAddition.bitOperation(charsA.length - 1, charsB.length - 1, result.length - 1, charsA, charsB, false, result);

        return result[0] == '\u0000' ? new String(result, 1, result.length - 1) : new String(result);
    }

    public static void bitOperation(int indexA, int indexB, int index, char[] charsA, char[] charsB, boolean isCarry, char[] chars) {
        char charA = '0', charB = '0';
        if (indexA == -1 && indexB == -1) {
            if (isCarry) {
                chars[index--] = '1';
            }
        } else {
            if (indexA != -1) {
                charA = charsA[indexA--];
            }

            if (indexB != -1) {
                charB = charsB[indexB--];
            }

            boolean judgeIsCarry = isCarry ? (charA == '1' || charB == '1') : (charA == '1' && charB == '1');
            chars[index--] = judgeIsCarry ? (isCarry && charA == '1' && charB == '1') ? '1' : '0' : (!isCarry && charA == '0' && charB == '0') ? '0' : '1';
            bitOperation(indexA, indexB, index, charsA, charsB, judgeIsCarry, chars);
        }
    }
}
